package cn.yangliu.tools;

import cn.hutool.core.lang.Snowflake;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import java.io.Serializable;
import java.util.Objects;

/**
 * the type of com-tool
 *
 * <p>
 * .
 *
 * @author 杨柳
 * @date 2021-09-29
 */
public class SnowflakeIdGenerator implements IdentifierGenerator {

    private static final Snowflake SNOWFLAKE = new Snowflake();

    /**
     * id生成逻辑
     *
     * @param session  SharedSessionContractImplementor
     * @param object 数据对象
     * @return id
     * @throws HibernateException 异常
     */
    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        Serializable identifier = session.getEntityPersister(null, object)
                .getClassMetadata().getIdentifier(object, session);
        if (Objects.nonNull(identifier)) {
            return identifier;
        }
        return SNOWFLAKE.nextId();
    }

}
